#include <cassert>
#include <cmath>
#include "image_manager.h"
#include "matrix.h"
#include <Image.h>


void ImageManager::saveMatrix(Matrix& m, string file) {
	// Creo una imagen del tamanho que necesto con el fondo azul
	Image image(Geometry(m.rows(),m.cols()), "blue"); 

	// burocracia
	image.type(TrueColorType);
	image.modifyImage();

	for ( int i = 0; i < m.rows() ; ++i ) 
		for ( int j = 0; j < m.cols() ; ++j ) {
			Color c=getColor(m(i,j));
			image.pixelColor(i,j,c);
		}
	 
	// y la escribo 
	image.write(file);

}

void ImageManager::loadMatrix(string file, Matrix& m) {

	Image image(file);
	Geometry g= image.size();
	m= Matrix(g.width(), g.height());

	for(size_t i= 0; i<m.rows(); i++) {
		for(size_t j= 0; j<m.cols(); j++) {
			m(i,j)= getValue(image.pixelColor(i, j));
		}
	}
}

unsigned ImageManager::getValue(ColorRGB c) {
	unsigned red= (unsigned)ceil(c.red()*255);
	unsigned green= (unsigned)ceil(c.green()*255); 
	unsigned blue= (unsigned)ceil(c.blue()*255); 
	
/* 	cout << "\tred: " << red << endl; */
/* 	cout << "\tgreen: " << green << endl; */
/* 	cout << "\tblue: " << blue << endl; */
/* 	cout << endl; */

	return (red+green+blue)/3;
}

Color ImageManager::getColor(unsigned v) {
/* 	double red, green, blue; */

/* 	blue=((double) (v % 256))/255; */
/* 	green= ((double)((v >> 8)%256))/255; */
/* 	red= ((double)((v >> 16)%256))/255; */

	assert(v <= 255);	
	double colorValue= ((double)v)/255;
/* 	cout << "red = " << red << endl; */
/* 	cout << "green = " << green << endl; */
/* 	cout << "blue = " << blue << endl; */

	return ColorRGB(colorValue, colorValue, colorValue);
}
